package com.cdd.eduservice.controller;


import com.cdd.commonutils.R;
import com.cdd.eduservice.entity.EduChapter;
import com.cdd.eduservice.entity.chapter.ChapterVo;
import com.cdd.eduservice.service.IEduChapterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 课程 前端控制器
 * </p>
 *
 * @author cdd
 * @since 2021-02-02
 */
@RestController
@RequestMapping("/eduservice/edu-chapter")
@CrossOrigin
public class EduChapterController {

    @Autowired
    private IEduChapterService eduChapterService;

    // 课程大纲列表，根据课程ID查询
    @GetMapping("getChapterVideo/{courseId}")
    public R getChapterVideo(@PathVariable String courseId){

        List<ChapterVo> chapterAndVideo = eduChapterService.getChapterAndVideo(courseId);

        return R.ok().data("list",chapterAndVideo);
    }

    // 添加章节
    @PostMapping("addChapter")
    public R addChapter(@RequestBody EduChapter eduChapter){
        Date date = new Date();
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
        eduChapter.setGmtCreate(localDateTime);
        eduChapter.setGmtModified(localDateTime);
        eduChapterService.save(eduChapter);
        return R.ok();
    }

    //根据ID查询章节
    @GetMapping("getChapter/{chapterId}")
    public R getChapter(@PathVariable String chapterId) {
        EduChapter eduChapter = eduChapterService.getById(chapterId);
        return R.ok().data("data",eduChapter);
    }

    // 修改章节
    @PostMapping("updateChapter")
    public R updateChapter(@RequestBody EduChapter eduChapter){
        Date date = new Date();
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
        eduChapter.setGmtModified(localDateTime);
        eduChapterService.updateById(eduChapter);
        return R.ok();
    }

    // 删除章节
    @DeleteMapping("deleteChapter/{chapterId}")
    public R deleteChapter(@PathVariable String chapterId) {
        boolean result = eduChapterService.deleteChapter(chapterId);
        if(result) {
            return R.ok();
        } else {
            return R.error();
        }
    }

}

